package org.bright.config;


import org.apache.log4j.Logger;
import org.bright.entity.R;
import org.bright.enums.HttpEnum;
import org.bright.exception.BusinessException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理类
 */
@RestControllerAdvice
public class GlobalException {

    private static final Logger logger = Logger.getLogger(GlobalException.class.getName());

    /**
     * 捕获校验参数异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValid(MethodArgumentNotValidException e, HttpServletRequest request) {
        logger.error("请求地址{" + request.getRequestURI() + "}," +
                "{" + request.getMethod() + "}请求参数有误"
                + e.getBindingResult().getFieldError().getDefaultMessage());
        return R.fail(HttpEnum.VALIDATE_ERROR.getCode(),
                e.getBindingResult().getFieldError().getDefaultMessage());
    }


    /**
     * 请求方式异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        logger.error("请求地址{" + request.getRequestURI() + "}," +
                "不支持{" + request.getMethod() + "}请求");
        return R.fail(HttpEnum.BAD_METHOD.getCode(),HttpEnum.BAD_METHOD.getMessage());

    }

    @ExceptionHandler(BusinessException.class)
    public R handleBusinessException(BusinessException e, HttpServletRequest request) {
        logger.error("请求地址{" + request.getRequestURI() + "}," +
                "业务异常，code：{" + e.getCode() + "},msg：{" + e.getMessage() + "}");
        return R.fail(e.getCode(),e.getMessage());
    }
}
